package com.bbm.communitysystem.controller.chat;

import com.bbm.communitysystem.core.ai.Ai;
import com.bbm.communitysystem.core.domain.R;
import com.bbm.communitysystem.core.oss.OSS;
import com.bbm.communitysystem.domain.Role;
import com.bbm.communitysystem.domain.UserInfo;
import com.bbm.communitysystem.domain.dto.chat.ChatUserInfo;
import com.bbm.communitysystem.domain.vo.ChatVo;
import com.bbm.communitysystem.service.IRoleService;
import com.bbm.communitysystem.service.impl.UserInfoServiceImpl;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.vosk.Model;
import org.vosk.Recognizer;
import reactor.core.publisher.Flux;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Tag(name = "聊天模型控制器")
@Slf4j
@RestController
@RequestMapping("/chat")
@RequiredArgsConstructor
public class ChatController {

    private final OllamaChatModel ollamaChatModel;

    private final IRoleService roleService;

    private final UserInfoServiceImpl userInfoService;

    private final Ai ai;

    private final OSS oss;

    @GetMapping(value = "",produces = "text/event-stream")
    public Flux<ChatVo> chat(
            @RequestParam("content") String content,
                             @RequestParam("pageId") long pageId,
                             @RequestParam("userId") String userId
    ) {

        ChatUserInfo chatUserInfo = getChatUserInfo(userId);

        Integer[] status = {0};

        Flux<ChatVo> flux;

        if (chatUserInfo == null) {
            return null;
        }

        AtomicReference<Prompt> prompt = new AtomicReference<>();

        String s = intentionIdentify("我是" + chatUserInfo.getRoleName() + content);
        s = s.trim();
        StringBuilder originContent = new StringBuilder();

        if (!chatUserInfo.getRoleName().equals("admin")) {
            s = "2";
        }

        switch (s) {
            case "1":
                String userInfo = "我是"  + chatUserInfo.getRoleName();
                prompt.set(new Prompt( userInfo + "，" + content + ",不需要说明时间", OllamaOptions.builder()
                        .model("deepseek-r1:8b").build()));


                String finalContent2 = content;

                flux = Flux.create(sink -> {
                    ChatVo chatVo1 = new ChatVo();

                    chatVo1.setEvent("hint");
                    chatVo1.setIsShow("1");
                    chatVo1.setData("none");
                    chatVo1.setType("text");
                    chatVo1.setContent("正在思考中");

                    sink.next(chatVo1);

                    ai.chat(prompt.get(), userId, pageId, finalContent2).subscribe(chatVo -> {


                        if (chatVo.getEvent().equals("end")) {

                            chatVo.setEvent("message");
                            chatVo.setContent("\n");
                            sink.next(chatVo);


                            chatVo.setEvent("wait");

                            chatVo1.setContent("生成模板中");

                            sink.next(chatVo1);


                            String[] hint = {"""
                                    只提取该内容的公告标题
                                    """ + originContent.toString()};
                            prompt.set(new Prompt(hint[0], OllamaOptions.builder()
                                    .model("gemma2:9b").build()));


                            ai.chat(prompt.get(), userId, pageId, false).subscribe(chatVo2 -> {


                                if (chatVo2.getEvent().equals("end")) {

                                    if (status[0] == 1) {
                                        sink.complete();
                                    }

                                    if (status[0] == 0) {
                                        status[0] = 1;
                                    }

                                }

                                chatVo2.setEvent("message");
                                chatVo2.setData("Ann");
                                chatVo2.setType("title");
                                sink.next(chatVo2);

                            });

                            hint[0] = """
                                    不需要提取到公告的标题，只提取该内容的公告内容
                                    """ +  originContent.toString();

                            prompt.set(new Prompt(hint[0], OllamaOptions.builder()
                                    .model("gemma2:9b").build()));

                            ai.chat(prompt.get(), userId, pageId, false).subscribe(chatVo2 -> {

                                if (chatVo2.getEvent().equals("end")) {
                                    if (status[0] == 1) {
                                        sink.complete();
                                    }

                                    if (status[0] == 0) {
                                        status[0] = 1;
                                    }
                                }

                                chatVo2.setEvent("message");
                                chatVo2.setData("Ann");
                                chatVo2.setType("annContent");

                                sink.next(chatVo2);

                            });

                        }


                        sink.next(chatVo);
                        if (chatVo.getIsThink() != 1) {
                            originContent.append(chatVo.getContent());
                        }

                    });


                });


                return flux;

            default:

                prompt.set(new Prompt(content, OllamaOptions.builder()
                        .model("deepseek-r1:8b").build()));

                flux = Flux.create(sink -> {
                    ChatVo chatVo1 = new ChatVo();

                    chatVo1.setEvent("hint");
                    chatVo1.setIsShow("1");
                    chatVo1.setData("none");
                    chatVo1.setType("text");
                    chatVo1.setContent("正在思考中");
                    sink.next(chatVo1);

                    ai.chat(prompt.get(), userId, pageId).subscribe(chatVo -> {
                        sink.next(chatVo);

                        if (chatVo.getEvent().equals("end")) {
                            sink.complete();
                        }

                    });

                });


                return flux;
        }

    }


    public String intentionIdentify(String content) {
        String prompt = """
                你现在是一个判断器，根据条件判断这句话与哪个动作最合理.
                只返回序号即可：1.写公告 2.聊天 3.问题。
                判断语句：""" + content;

        Prompt prompt1 = new Prompt(prompt, OllamaOptions.builder()
                .model("qwen2:7b").build());

        ChatResponse call = ollamaChatModel.call(prompt1);

        String s = call.getResult().getOutput().getText();
        s = s.replaceAll("\n","");
        s = s.replaceAll("<think>.*?</think>", "");

        log.info(s);

        return s;
    }




    public ChatUserInfo getChatUserInfo(String userId) {

        ChatUserInfo chatUserInfo = new ChatUserInfo();

        UserInfo byId = userInfoService.getById(userId);

        chatUserInfo.setUserId(userId);
        chatUserInfo.setUserNick(byId.getUserNick());
        chatUserInfo.setContact(byId.getUserEmail());


        List<String> roleId = new ArrayList<>();

        List<String> roleName = new ArrayList<>();

        String userRoleId = byId.getUserRoleId();

        if (userRoleId.isEmpty()) {
            return null;
        }

        String[] split = userRoleId.split(",");

        for (String s : split) {
            if ("0".equals(s)) {
                roleId.add("用户");
                roleName.add("用户");
            } else {
                Role byId1 = roleService.getById(s);

                roleId.add(s);
                roleName.add(byId1.getRoleName());
            }
        }

        chatUserInfo.setRoleId(roleId.toString());

        chatUserInfo.setRoleName(roleName.toString().replace("[","").replace("]",""));


        return chatUserInfo;
    }





}
